<template>
  <div>
    <!-- 表格 -->

    <el-table v-loading="loading" ref="multipleTableRef" :data="deviceConcatTotal" :header-cell-style="{ background: '#fbfbfa', height: '60px' }" class="mode-table mode-tableBottom"
      @selection-change="handleSelectionChange">
      <!-- 复选框 -->
      <el-table-column type="selection">
        <template #header>
          <!-- <el-checkbox v-model="isAllSelected" @change="handleAllSelectedChange"></el-checkbox> -->
        </template>
        <template #default="{ row }">
          <el-checkbox v-model="row.checked" @change="handleCheckboxChange(row)"></el-checkbox>
        </template>
      </el-table-column>
      <el-table-column prop="DeviceImages" width="100px">
        <template #default="{ row }">
          <img :src="`${baseURL}/` + row.DeviceImages" alt="设备图" width="68.57" />
        </template>
      </el-table-column>
      <!-- 设备名称 -->
      <el-table-column label="设备与终端名称" width="300">
        <template #default="{ row }">
          <div class="total">
            <p class="DeviceAndTerminal">{{ row.DeviceSerialNo }}<span v-if="row.DeviceLocation">-{{ row.DeviceLocation }}</span></p>
            <p class="DeviceName" style="white-space: nowrap;">{{ row.DeviceName }}</p>
            <p class="DeviceAndTerminal" style="white-space: nowrap;">{{ row.TerminalName }}({{ row.TerminalIdentity }})</p>
          </div>
        </template>
      </el-table-column>
      <!-- 状态 -->
      <el-table-column label="状态" align="center">
        <template #default="{ row }">
          <div>
            <div v-if='!(fun4(row.TerminalIdentity)) && !((fun5(row.WorkStatus?.WorkStatus))?.namestatus) && !(fun7(row))'>暂无状态</div>
            <div v-else class="status">
              <img v-if="(fun7(row))?.icon" :src=(fun7(row))?.icon alt="这是一张图片" class="statusIcon">
              <!-- <img v-if="!(fun7(row.TerminalIdentity))?.icon" :src=(fun4(row.TerminalIdentity))?.icon alt="这是一张图片" class="statusIcon"> -->
              <!-- <img v-if="!(fun7(row.Terminal/Identity))?.icon && !(fun5(row.TerminalIdentity))?.icon" :src=(fun5(row.TerminalIdentity))?.icon alt="这是一张图片" class="statusIcon"> -->
              <img v-else :src=(formatStatusIcon(row.WorkStatus?.WorkStatus))?.icon alt="这是一张图片" class="statusIcon">
              <span>{{ (fun7(row)) ? (fun7(row))?.nameDesc : fun4(row.TerminalIdentity)?.namestatus || ((fun5(row.WorkStatus?.WorkStatus))?.namestatus) }}</span>
            </div>
          </div>
        </template>
      </el-table-column>
      <!--检测总数  -->
      <el-table-column label="检测总数" prop="TotalCount" align="center">
        <template #default="{ row }">
          <p v-if="!row.StatisticResults?.TotalCount">0</p>
          <!-- <p v-else>{{ row.StatisticResults.TotalCount }}</p> -->
          <p v-else>{{ (fun3(row.TerminalIdentity))?.StatisticResults?.TotalCount ? (fun3(row.TerminalIdentity))?.StatisticResults?.TotalCount : row.StatisticResults?.TotalCount }}</p>
        </template>
      </el-table-column>
      <!--好品率 -->
      <el-table-column label="好品率" prop="ProductGoodRate" align="center">
        <template #default="{ row }">
          <p v-if="!(row.StatisticResults)?.QualifiedRate && !(fun3(row.TerminalIdentity)?.StatisticResults)?.QualifiedRate">0%</p>
          <p v-else>{{ (fun3(row.TerminalIdentity))?.StatisticResults?.QualifiedRate ? ((fun3(row.TerminalIdentity)).StatisticResults?.QualifiedRate) / 10 :
            row.StatisticResults?.QualifiedRate / 10 }}%</p>
        </template>
      </el-table-column>
      <!--检测效率/h -->
      <el-table-column label="检测效率/h" align="center">
        <template #default="{ row }">
          <p v-if="!row.StatisticResults?.ProductionEfficiency && !(fun3(row.TerminalIdentity))?.StatisticResults.ProductionEfficiency">0</p>
          <p v-else>{{ (fun3(row.TerminalIdentity))?.StatisticResults?.ProductionEfficiency
            ? (fun3(row.TerminalIdentity))?.StatisticResults?.ProductionEfficiency
            : row.StatisticResults?.ProductionEfficiency
          }}</p>
        </template>
      </el-table-column>
      <!--当前模板-->
      <el-table-column label="检测模板" align="center" width="260px">
        <template #default="{ row }">
          <!-- {{ row.StatisticResults?.TemplateName }} -->
          <el-select @change="handlerSelectValue" v-model="row.TemplateName" :placeholder="row.StatisticResults?.TemplateName ? row.StatisticResults?.TemplateName : '暂无模板'"
            style="border: 1px solid#F2994A; opacity: 0.5;width:230px">
            <div v-if="!props">
              <el-option v-for=" Template  in  row.TemplateList " :label="Template.TemplateName" :key="Template.TemplateId"
                :value="`${Template.TemplateName},${Template.TemplateId},${row.TerminalIdentity}`" />
            </div>
            <div v-if="props">
              <el-option v-for=" Template  in  fun8(row.TerminalIdentity) " :label="Template.TemplateName" :key="Template.TemplateId"
                :value="`${Template.TemplateName},${Template.TemplateId},${Template.TerminalIdentity}`" />
            </div>

          </el-select>
          <!-- <el-select @change="handlerSelectValue" @click="handlerSelect(row.TerminalIdentity)" v-model="row.TemplateName" :placeholder="row.StatisticResults?.TemplateName"
            style="border: 1px solid#F2994A; opacity: 0.5;width:230px">
            <el-option v-for="Template in templateValue" :label="Template.TemplateName" :key="Template.TemplateId" :value="`${Template.TemplateName},${Template.TemplateId},${row.TerminalIdentity}`" />
          </el-select> -->
        </template>
      </el-table-column>
      <!-- 返回的响应 -->
      <el-table-column label="" property="name">
        <template #default="{ row }">
          <p class="Switch-production">
            <img :src='fun1(row.TerminalIdentity).icon || fun2(row.TerminalIdentity).icon' alt="">
            <span :class="{ 'red-font': fun1(row.TerminalIdentity).Desc == 'Detection not started' || fun1(row.TerminalIdentity).Desc == 'Started detection' }"
              style="margin-left: 10px; letter-spacing: 1px;">{{ fun2(row.TerminalIdentity).nameDesc ||
                fun1(row.TerminalIdentity).nameDesc }}</span>
          </p>
        </template>
      </el-table-column>
      <!--更多-->
      <el-table-column label="更多" prop="more" align="center">
        <template #default="{ row }">
          <router-link class="btn" :to="`/details/${row.TerminalIdentity}`"><el-button size="default" style="border: 1px solid #f2994a; color: #f2994a">
              详情
            </el-button>
          </router-link>
        </template>
      </el-table-column>
    </el-table>
    <!-- 开检、停检、换产、复位 -->
    <div class="mode-btn">
      <!-- 开检 -->
      <el-button v-for="item in BtnObj" :key="item.ServiceType" :class="{ btn: true, bg: item.ServiceType == 2 }" size="default" @click="Inspection(item.ServiceType)">
        <img :src="item.icon" :alt="item.btnName">
        <span class="btn-ziti">{{ item.btnName }}</span>
      </el-button>
    </div>

  </div>
</template>

<script lang="ts" setup>
// 导入SignalR
import * as signalR from "@microsoft/signalr";
import { ref, onMounted, computed, watch } from "vue";
import { ElNotification } from 'element-plus'
// serverConfig.json是一个JSON格式的配置文件，用于存储服务器的配置信息
import serverConfig from "../../../serverConfig.json";
//用户登录相关的小仓库
import { useDevicesStore } from "@/stores/devices";
//引入请求函数
import { reqBasic, reqChanged } from "@/api/device/device";

// 引入状态图
import running from "@/assets/status/running.svg"
import waiting from "@/assets/status/waiting.svg"
import bad from "@/assets/status/bad.svg"
import outline from "@/assets/status/outline.svg"
// 引入成功或者失败的图标
import success from "@/views/MonitorMode/img/result-successsvg.svg"
import error from "@/views/MonitorMode/img/result-error.svg"
// 引入四个按钮的图标
import workIcon from "@/assets/btn/workBtn.svg"
import resetIcon from "@/assets/btn/resetBtn.svg"
import stopIcon from "@/assets/btn/stopBtn.svg"
import changeIcon from "@/assets/btn/changeBtn.svg"
// 获取设备小仓库
const devicesStore = useDevicesStore();

// 定义基础路径
const baseURL = `http://${serverConfig.server.ip}:${serverConfig.server.port}${serverConfig.server.apiPath}`;
const baseURLIP = `http://${serverConfig.server.ip}`;

// 接收父组件传过来的数据
const props = defineProps(["devicecardWebscoket"]);
const prop: any = ref(props);

// 获取表格vc实例
const multipleTableRef = ref<any>()

// 定义基本服务信息的变量
const basicservicesWebscoket = ref<any>([]);
const ChangeservicesWebscoket = ref<any>([]);

//定义状态图标的变量 
const runninging = running
const outlineing = outline
const bading = bad
const waitinging = waiting
//定义成功或者失败图标的变量
const successImg = success
const errorImg = error
//定义四个按钮图标的变量
const workImg = workIcon
const resetImg = resetIcon
const stopImg = stopIcon
const changeImg = changeIcon
const BtnObj = [
  { btnName: '开检', ServiceType: 1, icon: workImg },
  { btnName: '复位', ServiceType: 3, icon: resetImg },
  { btnName: '换产', ServiceType: 4, icon: changeImg },
  { btnName: '停检', ServiceType: 2, icon: stopImg },
]
const loading = ref(true)

// 定义复选框状态
const checkedRows = ref<any>([]);
const multipleSelection = ref<any>([]);

// 复选框选中时执行的逻辑
const handleCheckboxChange = (row: any) => {
  // 执行选中逻辑
  const existingObjIndex = checkedRows.value.findIndex((obj: any) => obj?.TerminalIdentity === row?.TerminalIdentity);
  if (existingObjIndex !== -1) {
    // 如果存在相同id的对象，则删除该对象
    checkedRows.value.splice(existingObjIndex, 1);
  } else {
    // 如果不存在相同id的对象，则将newObj推入数组
    checkedRows.value.push(row);
  }
};

// 定义下拉框的值
const optionselectedValue = ref<any>([])

// 定义两个请求合并后的数据
const deviceConcatTotal = ref<any>();

// 卡片监控的实时数据
const websocketDevices = ref<any>([])
const selectedValue = ref<any>([])
const selectedValueName = ref('')
const selectedValueId = ref('')
const selectedValueTerminalty = ref('')
// 设备的卡片式综合数据
const deviceInfo = ref<any>([])

const isAllSelected = ref(false)

// 存储选中的模版
const optionsList = ref<any>([])
/*-------------------------onMounted-----------------------------*/
onMounted(async () => {
  basicServicesSockets()
  changedServiceSockets()
  //获取根据终端标识获取设备的卡片式综合数据
  await getDeviceInfo()
  await getTotal();
});
setTimeout(async () => {
  basicServicesSockets()
  changedServiceSockets()
  //获取根据终端标识获取设备的卡片式综合数据
  await getDeviceInfo()
  await getTotal();
}, 3000);
// --------------------------------------------------------------------------------------------------------------------------------------

/*-------------------------从仓库中拿数据-----------------------------*/
// 获取所有设备的卡片式综合数据
const devices: any = ref(computed(() => devicesStore.$state.devices));
// 获取根据终端标识符查询最后一条生产事件信息
// const lastProdeventinfo: any = ref(computed(() => devicesStore.$state.lastProdeventinfo));
// console.log(lastProdeventinfo.value, '9999');

//获取根据终端标识获取设备的卡片式综合数据
const getDeviceInfo = () => {
  const deviceInfoValue: any = ref(computed(() => devicesStore.$state.deviceInfo));
  deviceInfo.value = deviceInfoValue.value
}
// --------------------------------------------------------------------------------------------------------------------------------------



/*-------------------------websocket-----------------------------*/
// 基本服务
const basicServicesSockets = () => {
  // 定义SignalR服务器地址
  //链接到通信交互基本服务
  const connection2 = new signalR.HubConnectionBuilder()
    .withUrl(`${baseURLIP}:10751/basicservices`, {
      skipNegotiation: true,
      transport: signalR.HttpTransportType.WebSockets,
    }) // 替换为实际的SignalR服务器地址
    .withAutomaticReconnect()
    .configureLogging(signalR.LogLevel.Information) // 使用signalr-protocol-msgpack
    .build();
  //连接到通信交互基本服务
  connection2.on("BasicServicesReceived", (message) => {
    console.log("🚀 ~ file: monitormode.vue:275 ~ connection2.on ~ message:", message)
    // 查找数组中是否存在相同的 id 和 num
    const existingItem = basicservicesWebscoket.value.find((item: any) => item.TerminalIdentity == message.TerminalIdentity && item.ServiceType == message.ServiceType);
    if (!existingItem) {
      // 查找数组中是否存在相同的 id
      const existingIndex = basicservicesWebscoket.value.findIndex((item: any) => item.TerminalIdentity == message.TerminalIdentity);
      if (existingIndex !== -1) {
        // 如果存在相同的 id，但 num 不同，则进行替换
        basicservicesWebscoket.value.splice(existingIndex, 1, message);
      } else {
        // 如果 id 和 num 都不同，则进行追加
        basicservicesWebscoket.value.push(message);
      }
    }
  });

  // 开始连接
  //连接到通信交互基本服务
  connection2.start().then(() => { console.log("通信交互基本服务SignalR连接已建立"); }).catch((error) => { console.error("通信交互基本服务SignalR连接错误:", error); });
  // 关闭连接
  //连接到通信交互基本服务
  connection2.onclose(() => { console.log("通信交互基本服务SignalR连接已关闭"); });
}
// 换产服务
const changedServiceSockets = () => {
  // 定义SignalR服务器地址
  //链接到通信交互基本服务
  const connection3 = new signalR.HubConnectionBuilder()
    .withUrl(`${baseURLIP}:10751/changedservice`, {
      skipNegotiation: true,
      transport: signalR.HttpTransportType.WebSockets,
    }) // 替换为实际的SignalR服务器地址
    .withAutomaticReconnect()
    .configureLogging(signalR.LogLevel.Information) // 使用signalr-protocol-msgpack
    .build();
  //连接到通信交互换产服务
  connection3.on("ChangedServiceReceived", (message) => {
    console.log(message, 'message');

    // 查找数组中是否存在相同的 id 和 num
    const existingItem = ChangeservicesWebscoket.value.find((item: any) => item.TerminalIdentity == message.TerminalIdentity && item.ResponseDesc == message.ResponseDesc);
    if (!existingItem) {   //没有找到id和描述都一样的
      // 查找数组中是否存在相同的 id
      const existingIndex = ChangeservicesWebscoket.value.findIndex((item: any) => item.TerminalIdentity == message.TerminalIdentity);
      if (existingIndex !== -1) {  // 找的了id一样的
        ChangeservicesWebscoket.value.splice(existingIndex, 1, message);
      } else {   // 没有找到id一样的
        ChangeservicesWebscoket.value.push(message);
      }
    } else {//找到id和描述都一样的
      ChangeservicesWebscoket.value.splice(existingItem, 1, message);
    }
  });

  // 开始连接
  //连接到通信交互换产服务
  connection3.start().then(() => { console.log("通信交互换产服务SignalR连接已建立"); }).catch((error) => { console.error("通信交互换产服务SignalR连接错误:", error); });

  // 关闭连接
  //连接到通信交互换产服务
  connection3.onclose(() => { console.log("通信交互换产服务SignalR连接已关闭"); });
}
// --------------------------------------------------------------------------------------------------------------------------------------
// 将两个数组的对应项进行合并
const getConcatTotal = () => {
  if (prop.value.devicecardWebscoket) {
    devices.value = prop.value.devicecardWebscoket
  }
  const deviceConcatTotal = devices.value.map((item1: any) => {
    const item2 = deviceInfo.value.find((item2: any) => item2.TerminalIdentity === item1.TerminalIdentity)
    return {
      ...item1,
      ...item2
    }
  });
  return deviceConcatTotal
};

// 将三个数组的对应项进行合并
const getTotal = async () => {
  // 拿到两个数据合并的结果
  let ConcatTotal = await getConcatTotal();
  // 为每个元素添加一个selected属性来表示是否选中
  const resultTotal = ConcatTotal.map((obj: any) => {
    return {
      ...obj,
      selected: selectedValue.value?.includes(obj.TerminalIdentity)
    }
  })
  deviceConcatTotal.value = resultTotal;
  deviceConcatTotal.value && (loading.value = false)
};

const handlerSelectValue = (a: any) => {
  const hasTerminalty = optionsList.value.some((obj: any) => obj.selectedValueTerminalty == a.split(',')[2]);

  if (hasTerminalty) {
    const hasTerminaltySelectedValueName = optionsList.value.some((obj: any) => obj.selectedValueTerminalty === a.split(',')[2] && obj.selectedValueName === a.split(',')[0]);

    if (!hasTerminaltySelectedValueName) {
      const index = optionsList.value.findIndex((obj: any) => obj.selectedValueTerminalty === a.split(',')[2]);
      if (index !== -1) {
        optionsList.value[index] = { selectedValueTerminalty: a.split(',')[2], selectedValueId: a.split(',')[1], selectedValueName: a.split(',')[0] };
      }
    }
  } else {
    optionsList.value.push({ selectedValueTerminalty: a.split(',')[2], selectedValueId: a.split(',')[1], selectedValueName: a.split(',')[0] })
  }

  // selectedValueName.value = a.split(',')[0]
  // selectedValueId.value = a.split(',')[1]
  // selectedValueTerminalty.value = a.split(',')[2]

}

const fun6 = (row: any) => {
  if (row.TerminalIdentity == selectedValueTerminalty.value) {
    return selectedValueName.value
  }
}




/*-------------------------四个按钮事件的相应-----------------------------*/
const fun1 = (row: any) => {
  let ServiceInfoValue: any = ''
  if (row) {
    const ServiceType = basicservicesWebscoket.value.find((item: any) => {
      if (row && item.TerminalIdentity == row) {
        ServiceInfoValue = formatDesc(item.ResponseDesc)
      }
    })
    
    return ServiceInfoValue
  }
}

const fun2 = (row: any) => {
  let ChangeInfoValue: any = ''
  if (row) {
    const ServiceType = ChangeservicesWebscoket.value.find((item: any) => {
      if (row && item.TerminalIdentity == row) {
        ChangeInfoValue = formatDesc(item.ResponseDesc)
      }
    })
    return ChangeInfoValue
  }
}

const fun5 = (row: any) => {
  return formatStatusIcon(row)
}

// 点击按钮以后返回数据切换的状态
const fun7 = (row: any) => {
  let ChangestatusValue: any = ''
  if (row && basicservicesWebscoket.value) {
    const ServiceType = basicservicesWebscoket.value.find((item: any) => {
      if (item.TerminalIdentity == row.TerminalIdentity) {
        ChangestatusValue = formatIcon(item.ResponseDesc)
        if (ChangestatusValue?.nameDesc == '开检') {
          row.WorkStatus.WorkStatus = 'Work'
        }
        if (ChangestatusValue?.nameDesc == '待机') {
          row.WorkStatus.WorkStatus = 'Standby'
        }
      }
    })
    return ChangestatusValue
  }
}

const formatDesc = (Desc: any) => {
  const statusList = [
    { nameDesc: '停检成功', Desc: 'Successfully Stopped', icon: successImg },
    { nameDesc: '开检成功', Desc: 'Successfully started', icon: successImg },
    { nameDesc: '复位成功', Desc: 'Successfully Reset', icon: successImg },
    { nameDesc: '换产成功', Desc: 'Successfully Replaced', icon: successImg },
    { nameDesc: '停检失败', Desc: 'Detection not started', icon: errorImg },
    { nameDesc: '开检失败', Desc: 'Started detection', icon: errorImg }
  ]
  const foramtData: any = statusList.find((item) => item.Desc == Desc)
  return foramtData
}


// 状态一列的方法
const formatStatusIcon = (status: any) => {
  const statusList = [
    { namestatus: '开检', status: 'Work', icon: runninging },
    { namestatus: '待机', status: 'Standby', icon: waitinging },
    { namestatus: '故障', status: 'Fault', icon: bading },
    { namestatus: '离线', status: 'Offline', icon: outlineing }
  ]
  const foramtData: any = statusList.find((item) => item.status == status)
  if (!foramtData) return
  // const IconComponent = foramtData.icon; // 获取与状态对应的图标组件
  return foramtData
}

const formatIcon = (Desc: any) => {
  const statusList = [
    { nameDesc: '待机', Desc: 'Successfully Stopped', icon: waitinging },
    { nameDesc: '开检', Desc: 'Successfully started', icon: runninging },
    { nameDesc: '复位', Desc: 'Successfully Reset' },
    { nameDesc: '888', Desc: 'Successfully Replaced' }
  ]
  const foramtData: any = statusList.find((item) => item.Desc == Desc)
  return foramtData
}
const fun3 = ref();
const fun4 = ref();
const fun8 = ref();
/*-------------------------监听事件-----------------------------*/
/*------------------------- 动态数据    每行的数值变化-----------------------------*/
watch(prop.value.devicecardWebscoket, (value) => {
  if (value.length > 0) {
    websocketDevices.value = value
    fun3.value = (row: any) => {
      const ServiceType = websocketDevices.value.find((item: any) => item.TerminalIdentity == row)
      if (!ServiceType) return
      return ServiceType
    }

    /*------------------------- 状态的变化-----------------------------*/
    fun4.value = (row: any) => {
      let ServiceInfo: any = ''
      if (row) {
        const ServiceType = websocketDevices.value.find((item: any) => item.TerminalIdentity == row)
        if (!ServiceType) return
        ServiceInfo = formatStatusIcon(ServiceType.WorkStatus.WorkStatus)
        return ServiceInfo.namestatus
      }
    }



    // 更新下拉框列表
    fun8.value = (Terminal: any) => {
      // console.log(Terminal,'Terminal');
      let ChangeInfoValue: any = []
      if (Terminal) {
        const ServiceType = websocketDevices.value.find((item: any) => item.TerminalIdentity == Terminal)
        if (!ServiceType) return
        ChangeInfoValue = ServiceType.TemplateList
        return ChangeInfoValue

      }
    }

  }
}, {
  immediate: true
})


// 处理全选按钮的变化
const handleSelectionChange = () => {
  isAllSelected.value = !isAllSelected.value
  deviceConcatTotal.value.forEach((row: any) => {
    row.checked = isAllSelected.value;
  });
  if (isAllSelected.value == false) {
    checkedRows.value = []
  } else {
    deviceConcatTotal.value.forEach((row: any) => {
      checkedRows.value.push(row);
    });
  }
};



/*-------------------------点击按钮-----------------------------*/
const Inspection = async (num: any) => {
  //获取根据终端标识获取设备的卡片式综合数据
  // await getDeviceInfo()
  // await getTotal();
  if (checkedRows.value.length > 0) {
    // console.log(checkedRows.value, 'checkedRows.value');

    checkedRows.value.forEach(async (item: any) => {
      if (item?.WorkStatus.WorkStatus == "Work") {
        // 点击开检按钮
        if (num == 1) {

          ElNotification({
            title: `${item.TerminalIdentity}`,
            message: "已开检，无法再次开检",
            type: 'warning',
            position: 'top-left',
          })
        }
        // 点击停检按钮
        if (num == 2) {
          try {
            let res = await reqBasic({ TerminalIdentity: item.TerminalIdentity, ServiceType: 2 })
            if (res.Desc == null) {
              //    // 提示用户
              ElNotification({
                title: `${item.TerminalIdentity}`,
                message: '停检指令已发送成功',
                type: 'success',
                position: 'top-left',
              })
            }
          } catch (error) {
            ElNotification({
              title: `${item.TerminalIdentity}`,
              message: "停检指令已发送失败",
              type: 'error',
              position: 'top-left',
            })
          }
        }
        // 点击复位按钮
        if (num == 3) {
          ElNotification({
            title: `${item.TerminalIdentity}`,
            message: "处于'开检状态'，无法执行'复位'操作",
            type: "info",
            position: 'top-left',
          })
        }
        // 点击换产按钮
        if (num == 4) {
          ElNotification({
            title: `${item.TerminalIdentity}`,
            message: "处于'开检状态'，无法执行'换产'操作",
            type: "info",
            position: 'top-left',
          })
        }
      }
      if (item?.WorkStatus.WorkStatus == "Standby") {//只有待机状态才能执行复位和换产
        // 点击开检按钮
        if (num == 1) {
          try {
            let res = await reqBasic({ TerminalIdentity: item.TerminalIdentity, ServiceType: 1 })
            // 提示用户
            ElNotification({
              title: `${item.TerminalIdentity}`,
              message: '开检指令已发送成功',
              type: 'success',
              position: 'top-left',
            })
          } catch (error) {
            ElNotification({
              title: `${item.TerminalIdentity}`,
              message: '开检指令发送失败',
              type: 'error',
              position: 'top-left',
            })
          }
        }
        // 点击停检按钮
        if (num == 2) {
          ElNotification({
            title: `${item.TerminalIdentity}`,
            message: " 处于'待机状态'，无法执行'停检'操作",
            type: "info",
            position: 'top-left',
          })
        }
        // 点击复位按钮
        if (num == 3) {
          try {
            let res = await reqBasic({ TerminalIdentity: item.TerminalIdentity, ServiceType: 3 })
            // 提示用户
            ElNotification({
              title: `${item.TerminalIdentity}`,
              message: '复位指令已发送成功',
              type: 'success',
              position: 'top-left',
            })
            await getDeviceInfo()
            await getTotal();
          } catch (error) {
            ElNotification({
              title: `${item.TerminalIdentity}`,
              message: '复位指令发送失败',
              type: 'error',
              position: 'top-left',
            })
          }
        }
        // 点击换产按钮
        if (num == 4) {
          if (optionsList.value.length < 1) return
          console.log(item);
          const aaa = optionsList.value.find((option: any) => option.selectedValueTerminalty == item.TerminalIdentity)

          let res = await reqChanged({ TerminalIdentity: item.TerminalIdentity, TemplateId: aaa.selectedValueId, TemplateName: aaa.selectedValueName })
          // localStorage.setItem("TerminalInfo", JSON.stringify({ "TerminalIdentity": item.TerminalIdentity, "TemplateName": selectedValueName.value }));
          item.StatisticResults.TemplateName = aaa.selectedValueName
          // 需要发请求
          try {
            // 提示用户
            ElNotification({
              title: `${item.TerminalIdentity}`,
              message: '换产指令已发送成功',
              type: 'success',
              position: 'top-left',
            })
            await getDeviceInfo()
            await getTotal();
          } catch (error) {
            console.log(error);

            ElNotification({
              title: `${item.TerminalIdentity}`,
              message: '换产指令发送失败',
              type: 'error',
              position: 'top-left',
            })
          }

        }
      }
      if (item?.WorkStatus.WorkStatus == "Fault") {
        // 点击开检按钮
        if (num == 1) {
          // 提示用户
          ElNotification({
            title: `${item.TerminalIdentity}`,
            message: "处于'故障状态'，无法执行'开检'操作",
            type: 'info',
            position: 'top-left',
          })
        }
        // 点击停检按钮
        if (num == 2) {
          ElNotification({
            title: `${item.TerminalIdentity}`,
            message: "处于'故障状态'，无法执行'停检'操作",
            type: "info",
            position: 'top-left',
          })
        }
        // 点击复位按钮
        if (num == 3) {
          ElNotification({
            title: `${item.TerminalIdentity}`,
            message: "处于'故障状态'，无法执行'复位'操作",
            type: "info",
            position: 'top-left',
          })
        }
        // 点击换产按钮
        if (num == 4) {
          ElNotification({
            title: `${item.TerminalIdentity}`,
            message: "处于'故障状态'，无法执行'换产'操作",
            type: "info",
            position: 'top-left',
          })
        }
      }
      if (item?.WorkStatus.WorkStatus == "Offline") {
        // 点击开检按钮
        if (num == 1) {
          // 提示用户
          ElNotification({
            title: `${item.TerminalIdentity}`,
            message: "处于'离线状态'，无法执行'开检'操作",
            type: 'info',
            position: 'top-left',
          })
        }
        // 点击停检按钮
        if (num == 2) {
          ElNotification({
            title: `${item.TerminalIdentity}`,
            message: "处于'离线状态'，无法执行'停检'操作",
            type: "info",
            position: 'top-left',
          })
        }
        // 点击复位按钮
        if (num == 3) {
          ElNotification({
            title: `${item.TerminalIdentity}`,
            message: "处于'离线状态'，无法执行'复位'操作",
            type: "info",
            position: 'top-left',
          })
        }
        // 点击换产按钮
        if (num == 4) {
          ElNotification({
            title: `${item.TerminalIdentity}`,
            message: "处于'离线状态'，无法执行'换产'操作",
            type: "info",
          })
        }
      }
    })
  } else {
    ElNotification({
      message: "请先选择列表中您要操作的设备项",
      type: "warning",
      position: 'top-left'
    })
  }
};
</script>

<style scoped lang="less">
/* 在小屏幕设备下，每个列的宽度变为100% */
@media (max-width: 767px) {
  .custom-table .el-table-column {
    flex: none;
    width: 100%;
  }
}

@media screen and (max-height: 1440px) {
  .mode-tableBottom {
    height: 1000px;
  }
}

@media screen and (max-height: 1080px) {
  .mode-tableBottom {
    height: 650px;
  }
}

:deep(.el-table th.el-table__cell) {
  text-align: center;
}

.el-notification {
  left: 50% !important;
  top: 50% !important;
  /*transform: translate(-50%, -50%);*/
}

.mode-table {
  width: 100%;
  margin-top: 16px;

  .el-table-column {
    width: minmax(50px, 1fr);
    /* 初始宽度为最小150px，最大为平均分配剩余空间 */
    /*flex: 1;*/
    /* 使用flex布局自动缩放 */
  }

  .Switch-production {
    display: flex;
    justify-content: center;
    color: #1AA367;

    .red-font {
      color: red;
    }
  }

  .total {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    color: #595959;
    font-family: Source Han Sans CN;
    font-size: 14px;
    font-style: normal;
    font-weight: 400;
    line-height: 22px;

    .DeviceName {
      color: #F2994A;
      font-family: Source Han Sans CN;
      font-size: 16px;
      font-style: normal;
      font-weight: 500;
      line-height: 24px;
      margin: 2px 0;
    }
  }

  .status {
    display: flex;
    align-items: center;
    justify-content: center;

    .statusIcon {
      width: 25px;
      height: 25px;
    }
  }
}

.mode-btn {
  width: 100%;
  display: flex;
  justify-content: end;
  background: #ffffff;
  padding: 16px 0;
  padding-right: 20px;

  .btn {
    background: #fc9030;
    width: 104px;
    border-radius: 6px;
    padding: 0 10px;

    .btn-ziti {
      margin: 8px;
      color: #ffffff;
    }
  }

  .bg {
    background: #ff636b;
  }
}
</style>
